<?php

namespace common\service;

use common\model\PlanModel;
use common\model\TaskMonthWorkHourRecordModel;
use common\model\WorkHourRecordModel;
use support\SingletonTrait;

class TaskService
{
    use SingletonTrait;

    /**
     * 查询任务详情
     * @param int $taskId
     * @return int[]
     */
    public function getDetail(int $taskId)
    {
        $res = [
            'task_id' => $taskId,
            'user_work_hour' => 0,// 用户累计工时
            'done' => false,//是否完成
            'start_time' => 0,// 开始时间
            'end_time' => 0,// 结束时间
            'plan_delivery_time' => 0, // 计划交付时间
            'executor' => null,// 执行人
        ];

        $executeInfo = model(WorkHourRecordModel::class)->where(['task_id' => $taskId])->order('id desc')->find();


        if (!empty($executeInfo) && $executeInfo['user_id'] > 0) {
            $user = teamones_request('teamones-im', 'user/find', [
                'param' => [
                    'filter' => [
                        'id' => $executeInfo['user_id'],
                    ]
                ]
            ]);
            $res['executor'] = $user['data'];
        }
        $planEndTime = model(PlanModel::class)->where(['episode_id' => $executeInfo['episode_id'], 'step_category_name' => $executeInfo['step_category_name']])->max('end_time');

        if (!empty($planEndTime)) {
            $res['plan_delivery_time'] = $planEndTime;
        }

        $least = model(TaskMonthWorkHourRecordModel::class)->where(['task_id' => $taskId])->order('id DESC')->find();
        if (!empty($least)) {
            $minWorkRecord = model(WorkHourRecordModel::class)->where(['task_id' => $taskId])->order('id ASC')->find();
            $res['start_time'] = $minWorkRecord['day_time'];
            if ($least['remain'] == 0) {
                $res['done'] = true;
                $maxWorkRecord = model(WorkHourRecordModel::class)->where(['task_id' => $taskId])->order('id DESC')->find();
                $res['end_time'] = $maxWorkRecord['day_time'];
            }
        }
        $res['user_work_hour'] = model(WorkHourRecordModel::class)->where(['task_id' => $taskId])->order('id ASC')->sum('hour');
        return $res;

    }
}
